<template>
  <div class="productClass divBox">
    <el-card class="box-card" shadow="hover">
      <template class="clearfix" v-slot:header>
        <div class="container">
          <el-form :model="tableCateFrom" label-width="72px" ref="tableCateRefs" class="tableCateCls">
            <el-row :gutter="20">
              <el-col v-bind="grid">
                <el-form-item label="分类状态：" class="selectFormWidth100">
                  <el-select v-model="tableCateFrom.isShow" placeholder="请选择分类状态" size="small" @change="getTableCateList">
                    <el-option label="全部" :value="-99"></el-option>
                    <el-option label="隐藏" :value="0"></el-option>
                    <el-option label="显示" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="tableCateAdd">添加分类</el-button>
        <el-tooltip :disabled="!disabledTableCate" class="ml10" effect="dark" content="本页至少选择一项" placement="bottom">
          <div style="display: inline-block;">
            <el-button :disabled="disabledTableCate" size="small" icon="el-icon-close" type="primary" @click="tableCateDel(null)">批量删除评论</el-button>
          </div>
        </el-tooltip>
      </template>
      <el-table
        ref="treeList"
        v-loading="tableCateLoading"
        :data="tableCateList"
        size="mini"
        class="table"
        highlight-current-row
        @select="rowSelectFun"
        @select-all="selectAllFun"
        @selection-change="selectionChangeFun"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" min-width="200"></el-table-column>
        <el-table-column prop="name" label="名称" min-width="200"></el-table-column>
        <template>
          <!--分类图标【start】-->
          <el-table-column label="分类图标" min-width="150">
            <template slot-scope="{ row }">
              <div class="demo-image__preview">
                <div class="tabBox_img" v-viewer>
                  <img v-lazy="$uploadURL(row.image)" :alt="$uploadURL(row.image)">
                </div>
              </div>
            </template>
          </el-table-column>
          <!--分类图标【end】-->

          <el-table-column label="排序" prop="sort" min-width="150" />

          <el-table-column label="状态" min-width="150">
            <template slot-scope="{ row }">
              <el-switch v-model.number="row.isShow" :active-value="1" :inactive-value="0" active-text="显示" inactive-text="隐藏" class="status" @change="tableCateChange(row)"></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" min-width="150">
            <template slot-scope="{ row }">
              <span>{{ row.createDateUTC | uctTimeFileter }}</span>
            </template>
          </el-table-column>

          <!--操作【start】-->
          <el-table-column fixed="right" label="操作" align="center" width="180">
            <template slot-scope="{ row }">
              <el-button v-if="row.pId === 0" type="text" size="small" @click="tableCate(row.id)">添加子目录</el-button>
              <el-divider v-if="row.pId === 0" direction="vertical"></el-divider>
              <el-button type="text" size="small" @click="tableCateEdit(row.id)">编辑</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button type="text" size="small" @click="tableCateDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
          <!--操作【end】-->
        </template>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import {
  getTableCateGroyApi,
  delTableCateApi,
  categroyUpdateStatus as patCateApi
} from '@/api/cate';

export default {
  name: "product_productClassify",
  data() {
    return {
      grid: {
        xl: 5,
        lg: 7,
        md: 12,
        sm: 12,
        xs: 24
      },
      tableCateList: [],
      del: [],
      tableCateLoading: false,
      disabledTableCate: true,
      tableCateFrom: {
        isShow: -99
      },
      isAll: false
    }
  },
  mounted() {
    this.getTableCateList();
  },
  methods: {
    toggleSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.treeList && this.$refs.treeList.toggleRowSelection(row, select);
        });
      };
    },
    setChildren(children, type) {
      children.map(j => {
        this.toggleSelection(j, type)
        if (j.children) {
          this.setChildren(j.children, type);
        };
      });
    },
    /**
     * 选择更改
     */
    selectionChangeFun(val) {
      this.$util.debounce(() => {
        this.$set(this, 'del', val.map(item => item.id));
        this.del.length !== 0 ? this.disabledTableCate = false : this.disabledTableCate = true;
      }, 300);
    },
    /**
     * 选择全部
     */
    selectAllFun(selection) {
      const isSelect = selection.some(item => {
        const tableDataIds = this.tableCateList.map(j => j.id);
        return tableDataIds.includes(item.id)
      });
      const isCancel = !this.tableCateList.every(el => {
        const selectIds = selection.map(j => j.id);
        return selectIds.includes(el.id);
      });

      if (isSelect) {
        selection.map(item => {
          if (item.children) {
            // 解决子组件没有被勾选到
            this.setChildren(item.children, true);
          };
        });
      };
      if (isCancel) {
        this.tableCateList.map(item => {
          if (item.children) {
            // 解决子组件没有被勾选到
            this.setChildren(item.children, false);
          };
        });
      };
    },
    /**
     * 选中父节点时，子节点一起选中取消
     */
    rowSelectFun(selection, row) {
      const hasSelect = selection.some(item => row.id === item.id);
      if (hasSelect) {
        if (row.children) {
          this.setChildren(row.children, true);
        }
      } else {
        if (row.children) {
          this.setChildren(row.children, false)
        };
      };
    },
    /**
     * 添加子目录
     */
    tableCate(id) {
      const _this = this;
      getTableCateGroyApi({
        isShow: -1
      }).then(res => {
        const list = res.map((item) => {
          return { id: item.id, name: item.name };
        });
        _this.$modal({
          componentProps: {
            pId: id,
            isEdit: 0,
            cate: list
          },
          component: (resolve) => require(['./components/tableCate'], resolve),
          props: {
            title: '添加分类',
            customClass: 'zdyDialogCls tableCateDialogCls',
            width: '100%',
            closeOnClickModal: false
          },
          methods: {
            getTableCate() {
              _this.getTableCateList();
            }
          }
        });
      });
    },
    /**
     * 分类状态改变时
     */
    tableCateChange(row) {
      patCateApi([
        {
          op: 'replace',
          path: '/isShow',
          value: row.isShow
        }
      ], row.id).then(() => {
        this.$message.success(row.isShow ? '显示成功' : '隐藏成功');
      }).catch(() => {
        !row.isShow ? row.isShow = 1 : row.isShow = 0;
      });
    },
    /**
     * 新增字段
     */
    newAttribute(list) {
      const _this = this;
      return list.map(item => {
        item.isChecked = false;
        if (item.children && item.children.length > 0) _this.$set(item, 'children', _this.newAttribute(item.children));
        return item;
      });
    },
    /**
     * 查询分类
     */
    getTableCateList() {
      this.$set(this, 'tableCateLoading', true);
      getTableCateGroyApi({
        isShow: this.tableCateFrom.isShow === -99 ? -1 : this.tableCateFrom.isShow,
        orderBy: 'sort desc'
      }).then(res => {
        this.$set(this, 'tableCateList', this.newAttribute(res));
        this.$set(this, 'tableCateLoading', false);
      }).catch(() => {
        this.$set(this, 'tableCateList', []);
        this.$set(this, 'tableCateLoading', false);
      });
    },
    /**
     * 编辑分类
     */
    tableCateEdit(id) {
      const _this = this;
      getTableCateGroyApi({
        isShow: -1
      }).then(res => {
        const list = res.map((item) => {
          return { id: item.id, name: item.name };
        });
        _this.$modal({
          componentProps: {
            id: id,
            isEdit: 1,
            cate: list
          },
          component: (resolve) => require(['./components/tableCate'], resolve),
          props: {
            title: '编辑分类',
            customClass: 'zdyDialogCls tableCateDialogCls',
            width: '100%',
            closeOnClickModal: false
          },
          methods: {
            getTableCate() {
              _this.getTableCateList();
            }
          }
        });
      });
    },
    /**
     * 添加分类
     */
    tableCateAdd() {
      const _this = this;
      getTableCateGroyApi({
        isShow: -1
      }).then(res => {
        const list = res.map((item) => {
          return { id: item.id, name: item.name };
        });
        _this.$modal({
          componentProps: {
            cate: list
          },
          component: (resolve) => require(['./components/tableCate'], resolve),
          props: {
            title: '添加分类',
            customClass: 'zdyDialogCls tableCateDialogCls',
            width: '100%',
            closeOnClickModal: false
          },
          methods: {
            getTableCate() {
              _this.getTableCateList();
            }
          }
        });
      });
    },
    /**
     * 删除分类
     * @param id
     */
    tableCateDel(id) {
      id || (this.del.length !== 0 && !this.disabledTableCate) ? this.$confirm(`删除商品分类`, {
        title: `删除商品分类`,
        message: this.$createElement('div', null, ['确定要删除商品分类吗？', '删除商品分类后将无法恢复，请谨慎操作！'].map((item) => this.$createElement('p', null, item))),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delTableCateApi(!id ? `(${this.del.join()})` : id).then(() => {
          this.$message.success('删除商品分类成功！');
          this.getTableCateList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: `已取消删除商品分类`
        });
      }) : this.$message.warning('请至少选择一条数据');
    }
  }
}
</script>

<style lang="scss">
  .el-dialog.tableCateDialogCls {
    max-width: 700px;
  }
</style>
